import $ from "jquery";
import styles from "./index.module.less";
import { getMovies } from "@/api/movie.js";
import { createMovieTag } from "../list";

let containerEl = null;

function init() {
  containerEl = $("<div>").addClass(styles.pager).appendTo("#app");
}

init();

/**
 * 根据传入的页码、页容量、总记录数，创建分页区域的标签
 * @params page 页码
 * @params limit 页容量
 * @params total 总页数
 */
export function createPagers(page, limit, total) {
  containerEl.empty();

  /**
   * 辅助函数，负责帮忙创建一个页码标签
   * @params text 标签的文本
   * @params status 标签的状态，空字符串-普通状态，disabled-禁用状态，active-选中状态
   */
  function createTag(text, status, targetPage) {
    const spanEl = $("<span>").appendTo(containerEl).text(text);
    const className = styles[status];
    spanEl.addClass(className);

    // 只有是普通样式时，才有事件
    if (status === "") {
      spanEl.on("click", async () => {
        const resp = await getMovies(targetPage, limit);
        createMovieTag(resp.data.movieList);
        createPagers(targetPage, limit, resp.data.movieTotal);
      });
    }
  }

  const pageNumber = Math.ceil(total / limit);

  createTag("|<<", page === 1 ? "disabled" : "", 1);
  createTag("<<", page === 1 ? "disabled" : "", page - 1);

  const maxCount = 10;
  const min = Math.max(Math.floor(page - maxCount / 2), 1);
  const max = Math.min(min + maxCount - 1, pageNumber);

  for (let i = min; i <= max; i++) {
    createTag(i, i === page ? "active" : "", i);
  }

  createTag(">>", page === pageNumber ? "disabled" : "", page + 1);
  createTag(">>|", page === pageNumber ? "disabled" : "", pageNumber);
}
